package com.zyf.system.controller;

import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.zyf.system.controller.dto.BasePageDto;
import com.zyf.system.controller.dto.UserAddDto;
import com.zyf.system.controller.dto.UserPageDto;
import com.zyf.system.controller.dto.UserUpdateDto;
import com.zyf.system.db.mysql.QUser;
import com.zyf.system.db.mysql.User;
import com.zyf.system.repository.UserRepository;
import com.zyf.system.until.Constant;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * @author 张云帆
 * 2025/3/25 13:53
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController{
    @Autowired
    private UserRepository userRepository;
    private final QUser qUser = QUser.user;
    @PostMapping("/getTree")
    @ApiOperation(value = "分页查询用户列表")
    public Map<String, Object> page(@Validated @RequestBody UserPageDto userPageDto){
        try {
            Pageable pageable = PageRequest.of(userPageDto.getPageNum() - 1, userPageDto.getPageSize());
            Predicate predicate = qUser.isNull().or(qUser.isNotNull());
            if(userPageDto.getRole() != null){
                predicate = ExpressionUtils.and(predicate, qUser.role.eq(userPageDto.getRole()));
            }
            if(userPageDto.getUsername() != null){
                predicate = ExpressionUtils.and(predicate, qUser.username.like("%"+userPageDto.getUsername()+"%"));
            }
            if(userPageDto.getIsDeleted() != null){
                predicate = ExpressionUtils.and(predicate, qUser.isDeleted.eq(userPageDto.getIsDeleted()));
            }
            if(userPageDto.getRealName() != null){
                predicate = ExpressionUtils.and(predicate, qUser.realName.like("%"+userPageDto.getRealName()+"%"));
            }
            Page<User> all = userRepository.findAll(predicate,pageable);
            return createResponse(Constant.SUCCESS, "查询成功", all);
        }catch (Exception e){
            return createResponse(Constant.FAIL, "分页查询用户列表异常", e.getMessage());
        }
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加用户")
    public Map<String, Object> add(@Validated @RequestBody UserAddDto userAddDto){
        try {
            if(userRepository.exists(qUser.username.eq(userAddDto.getUsername()))){
                return createResponse(Constant.FAIL, "用户名已存在", null);
            }
            User user = new User(userAddDto);
            return createResponse(Constant.SUCCESS, "添加用户成功", userRepository.save(user));
        }catch (Exception e){
            return createResponse(Constant.FAIL, "添加用户异常", e.getMessage());
        }
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改用户")
    public Map<String, Object> update(@Validated @RequestBody UserUpdateDto userUpdateDto){
        try {
            User user = userRepository.findById(userUpdateDto.getId()).orElse(null);
            if(user == null){
                return createResponse(Constant.FAIL, "用户不存在", null);
            }
            if(!userUpdateDto.getPhone().isEmpty()){
                user.setPhone(userUpdateDto.getPhone());
            }
            if(!userUpdateDto.getEmail().isEmpty()){
                user.setEmail(userUpdateDto.getEmail());
            }
            user.setRealName(userUpdateDto.getRealName());
            user.setRole(userUpdateDto.getRole());
            return createResponse(Constant.SUCCESS, "修改用户成功", userRepository.save(user));
        }catch (Exception e){
            return createResponse(Constant.FAIL, "修改用户异常", e.getMessage());
        }
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "删除用户")
    public Map<String, Object> delete(@Validated @NotNull @RequestParam Integer id){
        try{
            if(!userRepository.exists(qUser.id.eq(id))){
                return createResponse(Constant.FAIL, "用户不存在", "ID:" + id);
            }
            userRepository.deleteById(id);
            return createResponse(Constant.SUCCESS, "删除用户成功", null);
        }catch (Exception e){
            return createResponse(Constant.FAIL, "删除用户异常", e.getMessage());
        }
    }

    @DeleteMapping("/batchDelete")
    @ApiOperation(value = "批量删除用户")
    public Map<String, Object> batchDelete(@Validated @NotNull @RequestParam List<Integer> ids){
        try{
            for (Integer id : ids) {
                if(!userRepository.exists(qUser.id.eq(id))){
                    return createResponse(Constant.FAIL, "用户不存在", "ID:" + id);
                }
            }
            userRepository.deleteAllById(ids);
            return createResponse(Constant.SUCCESS, "批量删除用户成功", null);
        }catch (Exception e){
            return createResponse(Constant.FAIL, "批量删除用户异常", e.getMessage());
        }
    }

    @PostMapping("/resetPassword")
    @ApiOperation(value = "重置密码")
    public Map<String, Object> resetPassword(@Validated @NotNull @RequestParam("id") Integer id){
        try{
            User user = userRepository.findById(id).orElse(null);
            if(user == null){
                return createResponse(Constant.FAIL, "用户不存在", "ID:" + id);
            }
            user.setPassword("123456");
            return createResponse(Constant.SUCCESS, "重置密码成功", userRepository.save(user));
        }catch (Exception e){
            return createResponse(Constant.FAIL, "重置密码异常", e.getMessage());
        }
    }

    @PostMapping("/changeUsable")
    @ApiOperation(value = "修改用户可用状态")
    public Map<String, Object> changeUsable(@Validated @NotNull @RequestParam("id") Integer id){
        try{
            User user = userRepository.findById(id).orElse(null);
            if(user == null){
                return createResponse(Constant.FAIL, "用户不存在", "ID:" + id);
            }
            user.setIsDeleted(!user.getIsDeleted());
            return createResponse(Constant.SUCCESS, "修改用户可用状态成功", userRepository.save(user));
        }catch (Exception e){
            return createResponse(Constant.FAIL, "修改用户可用状态异常", e.getMessage());
        }
    }

    @GetMapping("/get")
    @ApiOperation(value = "查询用户")
    public Map<String, Object> get(@Validated @NotNull @RequestParam Integer id){
        try{
            User user = userRepository.findById(id).orElse(null);
            if(user == null){
                return createResponse(Constant.FAIL, "用户不存在", "ID:" + id);
            }
            if(user.getIsDeleted()){
                return createResponse(Constant.FAIL, "用户已停用", "ID:" + id);
            }
            return createResponse(Constant.SUCCESS, "查询用户成功", user);
        }catch (Exception e){
            return createResponse(Constant.FAIL, "查询用户异常", e.getMessage());
        }
    }

}
